package com.nth.rooster.core.dao;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.nth.rooster.core.entities.RamSystemSettings;
import com.nth.rooster.core.exception.NErrorCode;
import com.nth.rooster.core.exception.UnknownSystemKeyException;
import com.nth.rooster.core.utils.DBUtils;

@Component
public class DBUtilsDAO implements DBUtilsDaoI {

	static Logger LOGGER = Logger.getLogger(DBUtilsDAO.class);
	
	@Autowired
	private SessionFactory factory;

	public RamSystemSettings getSystemSettings(String settingKey) {
	
		LOGGER.info("Entered::Core::DBUtilsDAO::getSystemSettings::SettingKey" + settingKey);
		
		Session session = factory.openSession();
		
		Query fetchQuery = session.createQuery("from RamSystemSettings where settingKey=:settingKey");
		
		fetchQuery.setString("settingKey", settingKey);
		
		RamSystemSettings systemSettings = (RamSystemSettings)fetchQuery.uniqueResult();
		
		if (systemSettings==null) {
			throw new UnknownSystemKeyException(NErrorCode.UNDEFINED_SYSTEM_SETTING_KEY, settingKey);
		}
		
		DBUtils.closeSession(session);
		LOGGER.info("Entered::Core::DBUtilsDAO::getSystemSettings::SettingKey" + settingKey + "::Value::"  + systemSettings.getSettingValue());
		
		return systemSettings;
	}

	
	public void updateSystemSettings(RamSystemSettings systemSettings){
		LOGGER.info("Entered::Core::DBUtilsDAO::getSystemSettings::updateSystemSettings::settingKey" + systemSettings.getSettingKey() + "::Value::" + systemSettings.getSettingValue());
		
		Session session = factory.openSession();
		Transaction transaction = session.beginTransaction();
		
		session.update(systemSettings);

		transaction.commit();
		DBUtils.closeSession(session);
		LOGGER.info("Exit::Core::DBUtilsDAO::getSystemSettings::updateSystemSettings::settingKey" + systemSettings.getSettingKey() + "::Value::" + systemSettings.getSettingValue());
		
	} 
	

	

}
